$(document).ready(function () {
  // ----------------- 全局数据--------------------
  let username = '';
  let password = '';
  let rememberMe = false;

  // -----------------生命周期（立即执行函数） -----------------
  (function created() {
    bindEventListener();
  })()


  function bindEventListener() {

  }


  $('#form').on('submit', function (e) {
    e.preventDefault();

    // 获取表单数据
    username = $('#username').val();
    password = $('#password').val();
    rememberMe = $('#rememberMe').is(':checked');

    // 清除之前的错误消息
    $('#message').addClass('d-none');

    // 验证输入
    if (!username || !password) {
      showMessage('Please input username and password!');
      return;
    }

    // 显示加载状态
    const $loginBtn = $('#login-btn');
    const btnText = $loginBtn.html();
    $loginBtn.prop('disabled', true);
    $loginBtn.html('<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>Logging in ...');

    login({username, password}).then(response => {
      if (response.code === 200) {
        setToken(rememberMe,response.data);
        window.location.href = 'index.html';
      } else if (response.code === 400) {
        // 恢复按钮状态
        $loginBtn.prop('disabled', false);
        $loginBtn.html(btnText);
        showMessage(response.message);
      }
    })
  });

  function showMessage(message) {
    $('#message').text(message).removeClass('d-none');
  }
});